package com.example.learn_spring_boot3.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.learn_spring_boot3.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {

    // 指定为自动生成id, 实体类的字段为id, 数据库字段对应为id
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    // 编写批量插入sql
    @Insert({
            "<script>",
            "INSERT INTO learn_spring_boot3.user (id, name, age, sex, password) VALUES ",
            "<foreach collection='list' item='item' index='index' separator=','>",
            "(#{item.id}, #{item.name}, #{item.age}, #{item.sex}, '000000')",
            "</foreach>",
            "</script>"
    })
    int addBatch(@Param("list") List<User> list);

    // 查询所有的用户
    @Select("SELECT * FROM learn_spring_boot3.user")

    // 这里定义结果集映射
    @Results({
            // 字段一一对应
            @Result(column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "age", property = "age"),
            @Result(column = "sex", property = "sex"),

            @Result(
                    // 使用id去查询, 对应实体类的orders字段, 返回值类型为 List
                    column = "id", property = "orders", javaType = List.class,
                    // 一对多查询, select表示引用其它mapper的方法, 会把 id 的值传给他
                    many = @Many(select = "com.example.learn_spring_boot3.mapper.UserOrderMapper.selectByUid")
            ),
    })
    List<User> selectAllUserAndOrders();

    @Select("SELECT * FROM learn_spring_boot3.user WHERE id=#{id}")
    User selectById(int id);
}
